import mysql from 'mysql';
import { MYSQL_CONN_OPTIONS } from '../config/config';
import {isEmpty} from '../controllers/utils';
import {sendLogToEmail} from '../controllers/logger';

const pool = mysql.createPool(MYSQL_CONN_OPTIONS);
pool.on('connection', function (connection) {
    connection.query('SET SESSION auto_increment_increment=1');
});
pool.on('error', function (err) {
    console.info(`mysql err:${err.code }`);
});

export function getPool() {
    return pool;
}

export function exesql(sql, params = []) {
    return new Promise(function (resolve, reject) {
        pool.query(sql, params, function (err, rows) {
            let dic = {};
            if (err) {
                const errMsg = 'err=' + err.stack + '|sql=' + sql + 'params=' + JSON.stringify(params);
                sendLogToEmail(errMsg);
                Object.assign(dic, { err: new Error(errMsg), result: null })
            } else {
                Object.assign(dic, { err: null, result: rows })
            }
            return resolve(dic);
        })
    })
}

export function updateTable(data, table, keyfield) {
    return new Promise(function (resolve, reject) {
        let params = [];
        let setstr = '';
        for (let p in data) {
            if (p == keyfield) {
                continue;
            }
            if (isEmpty(data[p])) {
                continue;
            }
            if (setstr != '') {
                setstr += ','
            }
            if (data[p] == 'CURRENT_TIMESTAMP') {
                setstr += p + '=CURRENT_TIMESTAMP'
            } else {
                setstr += p + '=?'
                if (typeof (data[p]) == 'object') {
                    data[p] = JSON.stringify(data[p])
                }
                params.push(data[p])
            }
        }
        params.push(data[keyfield])
        const sql = 'update ' + table + ' set ' + setstr + ' where ' + keyfield + '=?'
        pool.query(sql, params, function (err, rows) {
            if (err) {
                const errMsg = 'err=' + err.stack + '|sql=' + sql + 'params=' + JSON.stringify(params);
                sendLogToEmail(errMsg);
                return reject(err);
            } else {
                return resolve(rows);
            }
        })
    })
}

export function insertTable(data, table) {
    return new Promise(function (resolve, reject) {
        let params = [];
        let fields = '';
        let values = '';
        for (let p in data) {
            if (fields != '') {
                fields += ','
                values += ','
            }
            fields += p;
            values += '?'
            if (typeof (data[p]) == 'object') {
                data[p] = JSON.stringify(data[p])
            }
            params.push(data[p]);
        }
        const sql = 'insert into ' + table + ' (' + fields + ') values (' + values + ') ';
        pool.query(sql, params, function (err, rows) {
            if (err) {
                const errMsg = 'err=' + err.stack + '|sql=' + sql + 'params=' + JSON.stringify(params);
                sendLogToEmail(errMsg);
                return resolve({err:new Error(errMsg),result:rows});
            } else {
                return resolve({err:null,result:rows});
            }
        })
    })
}


// 事务插入数据
export function transaction(sqls) {
    return new Promise(function (resolve, reject) {
        pool.getConnection(function (err, connection) {
            if (err) {
                console.log("GetConnection Err :", err.code);
                reject(err);
                return;
            }
            // 处理业务逻辑,开始事物
            connection.beginTransaction(function (err) {
                if (err) {
                    console.log("beginTransaction Err :", err.code);
                    reject(err);
                    return;
                }
                let promises = []
                sqls.forEach(sql => {
                    let promise = new Promise(function (resolve, reject) {
                        connection.query(sql, [], function (err, rows) {
                            if (err) {
                                console.log(err);
                                return resolve(-1);
                            }
                            return resolve(0);
                        })
                    });
                    promises.push(promise);
                });

                Promise.all(promises).then(function (values) {
                    console.log('提交');
                    connection.commit(function (err, info) {
                        console.log(values);
                        if (err) {
                            connection.rollback(function (err) {
                                connection.release();
                                return reject(err);
                            });
                        } else {
                            connection.release();
                            return resolve(info);
                        }
                    })
                });
            })
        });
    });
};